package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.ItemDTO;
import com.ruoyi.system.domain.dto.TaskUninstallDTO;
import com.ruoyi.system.domain.dto.TaskCreateDTO;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ITbTaskService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 推送任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
@Slf4j
public class TbTaskServiceImpl implements ITbTaskService {
    @Autowired
    private TbTaskMapper tbTaskMapper;

    @Autowired
    private TbTaskDetailMapper tbTaskDetailMapper;

    @Autowired
    private TbAppCatalogMapper tbAppCatalogMapper;

    @Autowired
    private TbAppVersionMapper tbAppVersionMapper;

    @Autowired
    private TbDataPackageMapper tbDataPackageMapper;

    @Autowired
    private TbTaskTargetMapper tbTaskTargetMapper;


    @Autowired
    private TbAirplaneMapper tbAirplaneMapper;

    @Autowired
    private TbDeviceMapper tbDeviceMapper;


    @Autowired
    private TbDeviceInfoMapper tbDeviceInfoMapper;

    @Autowired
    private TbDeviceAppsMapper tbDeviceAppsMapper;


    /**
     * 查询推送任务
     *
     * @param id 推送任务主键
     * @return 推送任务
     */
    @Override
    public TbTask selectTbTaskById(Long id) {
        return tbTaskMapper.selectTbTaskById(id);
    }

    /**
     * 查询推送任务列表
     *
     * @param tbTask 推送任务
     * @return 推送任务
     */
    @Override
    public List<TbTask> selectTbTaskList(TbTask tbTask) {
        return tbTaskMapper.selectTbTaskList(tbTask);
    }

    /**
     * 新增推送任务
     *
     * @param tbTask 推送任务
     * @return 结果
     */
    @Override
    public int insertTbTask(TbTask tbTask) {
        tbTask.setCreateTime(DateUtils.getNowDate());
        return tbTaskMapper.insertTbTask(tbTask);
    }

    /**
     * 修改推送任务
     *
     * @param tbTask 推送任务
     * @return 结果
     */
    @Override
    public int updateTbTask(TbTask tbTask) {
        tbTask.setUpdateTime(DateUtils.getNowDate());
        return tbTaskMapper.updateTbTask(tbTask);
    }

    /**
     * 批量删除推送任务
     *
     * @param ids 需要删除的推送任务主键
     * @return 结果
     */
    @Override
    public int deleteTbTaskByIds(Long[] ids) {
        if (tbTaskMapper.deleteTbTaskByIds(ids) > 0) {

            return tbTaskDetailMapper.deleteTbTaskDetailByTaskIds(ids);
        }
        return 0;
    }

    /**
     * 删除推送任务信息
     *
     * @param id 推送任务主键
     * @return 结果
     */
    @Override
    public int deleteTbTaskById(Long id) {
        return tbTaskMapper.deleteTbTaskById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean CreateTaskAnddetailsToDevice(TaskCreateDTO dto) {
        // 1. 参数校验
        validateTaskCreateDTO(dto);

        // 2. 创建主任务
        TbTask tbTask = createMainTask(dto);

        // 3. 创建任务详情
        List<TbTaskTarget> taskTargets = createTaskDetailsAndTargets(dto, tbTask.getId());

        // 4. 批量插入设备目标
        if (!taskTargets.isEmpty()) {
            tbTaskTargetMapper.batchInsert(taskTargets);
        }

        return Boolean.TRUE;
    }


    // 创建任务详情和目标设备
    private List<TbTaskTarget> createTaskDetailsAndTargets(TaskCreateDTO dto, Long taskId) {
        List<TbTaskTarget> taskTargets = new ArrayList<>();
        String username = SecurityUtils.getLoginUser().getUsername();
        Date now = DateUtils.getNowDate();
        int orderId = 1;
        for (ItemDTO item : dto.getItems()) {
            TbTaskDetail taskDetail = new TbTaskDetail();
            taskDetail.setTaskId(taskId);
            taskDetail.setOrderId(orderId);
            orderId++;
            taskDetail.setPackageVersioncode(item.getPackageVersioncode());
            List<Long> deviceIds = null;
            if (dto.getDevSNs() == null && dto.getPlaneCodes() == null) {
                // 情况1：两个参数都为空，获取所有已登记注册的设备ids
                deviceIds = tbDeviceMapper.selectOnlineAndRegisteredDeviceIds();
            } else if (dto.getDevSNs() != null && !dto.getDevSNs().isEmpty() && (dto.getPlaneCodes() == null || dto.getPlaneCodes().isEmpty())) {
                // 情况2：只有设备SN列表，按设备SN查询
                List<TbDeviceVO> tbDeviceVOS = tbDeviceMapper.selectListByDeviceSns(dto.getDevSNs());
                deviceIds = tbDeviceVOS.stream().map(TbDeviceVO::getId).collect(Collectors.toList());
            } else if (dto.getPlaneCodes() != null && !dto.getPlaneCodes().isEmpty() && (dto.getDevSNs() == null || dto.getDevSNs().isEmpty())) {
                // 情况3：只有飞机代码列表，按飞机代码查询
                List<TbDevice> tbDevices = tbDeviceMapper.selectListByPlaneCodes(dto.getPlaneCodes());
                deviceIds = tbDevices.stream().map(TbDevice::getId).collect(Collectors.toList());
            }
            taskDetail.setDeviceCount(deviceIds.size());
            // 设置包信息
            setPackageInfo(taskDetail, item);
            // 设置通用信息
            taskDetail.setCreateBy(username);
            taskDetail.setCreateTime(now);

            if (tbTaskDetailMapper.insertTbTaskDetail(taskDetail) <= 0) {
                throw new ServiceException("创建任务详情失败");
            }

            // 准备目标设备数据
            taskTargets.addAll(deviceIds.stream().map(deviceId -> {
                TbTaskTarget taskTarget = new TbTaskTarget();
                taskTarget.setTaskDetailId(taskDetail.getId());
                taskTarget.setDeviceId(deviceId);
                taskTarget.setStatus(0);
                taskTarget.setCreateBy(username);
                taskTarget.setCreateTime(now);
                return taskTarget;
            }).collect(Collectors.toList()));
        }

        return taskTargets;
    }


    // 设置包信息
    private void setPackageInfo(TbTaskDetail taskDetail, ItemDTO item) {
        // 检查是否是应用版本
        TbAppVersion tbAppVersion = tbAppVersionMapper.selectBypackageNameAndVersion(item.getPackageName(), item.getPackageVersionnumber(), item.getPackageVersioncode());
        if (tbAppVersion != null) {
            taskDetail.setPushPackageType(1);
            taskDetail.setPackageId(tbAppVersion.getId());
            TbAppCatalog tbAppCatalog = tbAppCatalogMapper.selectByPackageId(tbAppVersion.getPackageId());
            if (tbAppCatalog != null) {
                taskDetail.setAppName(tbAppCatalog.getAppName());
            }
            taskDetail.setPackageVersionnumber(tbAppVersion.getPackageVersionnumber());
            taskDetail.setPackageSize(tbAppVersion.getPackageSize());
            taskDetail.setTaskType(3);
            return;
        }

        // 检查是否是数据包
        TbDataPackage tbDataPackage = tbDataPackageMapper.selectDataPackageByPackversionCodes(item.getPackageName(), item.getPackageVersioncode(), item.getPackageVersionnumber());
        if (tbDataPackage != null) {
            taskDetail.setPushPackageType(2);
            taskDetail.setPackageId(tbDataPackage.getId());
            taskDetail.setPackageName(tbDataPackage.getPackageName());
            taskDetail.setPackageVersionnumber(tbDataPackage.getPackageVersionnumber());
            taskDetail.setPackageSize(tbDataPackage.getPackageSize());
            taskDetail.setTaskType(1);
            return;
        }

        throw new IllegalArgumentException("找不到匹配的包版本: " + item.getPackageVersioncode());
    }


    @Override
    public AviationAppStatsVO publishAllDeviceInfo(List<ItemDTO> itemDTOS) {
        AviationAppStatsVO aviationAppStatsVO = new AviationAppStatsVO();
        //查询 飞机总数, 以及关联的设备总数, 在线设备数, 预计流量
        int deviceCount = tbDeviceMapper.selectCountrel();
        aviationAppStatsVO.setTotalDevicesCount(deviceCount);
        int onlineDeviceCount = tbDeviceMapper.selectDeviceCountOnline();
        aviationAppStatsVO.setOnlineDevicesCount(onlineDeviceCount);

        // 3. 查询去重飞机号并统计飞机数
        List<String> airplaneCodes = tbDeviceMapper.selectplaneCodeList();
        airplaneCodes = airplaneCodes.stream().filter(Objects::nonNull) // 过滤null值
                .distinct().collect(Collectors.toList());
        aviationAppStatsVO.setInstalledAircraftCount(airplaneCodes.size());

        // 4. 计算预计总流量
        BigDecimal estimatedTraffic = BigDecimal.ZERO;

        if (CollectionUtils.isNotEmpty(itemDTOS)) {
            for (ItemDTO item : itemDTOS) {
                // 检查是否是应用版本
                TbAppVersion appVersion = tbAppVersionMapper.selectByPackageNameAndCodeAndNum(item.getPackageName(), item.getPackageVersioncode(), item.getPackageVersionnumber());
                if (appVersion != null) {
                    estimatedTraffic = estimatedTraffic.add(BigDecimal.valueOf(appVersion.getPackageSize()).multiply(BigDecimal.valueOf(deviceCount)));
                }

                // 检查是否是数据包
                TbDataPackage dataPackage = tbDataPackageMapper.selectByPackageNameAndVersion(item.getPackageName(), item.getPackageVersionnumber(), item.getPackageVersioncode());
                if (dataPackage != null) {
                    estimatedTraffic = estimatedTraffic.add(BigDecimal.valueOf(dataPackage.getPackageSize()).multiply(BigDecimal.valueOf(deviceCount)));
                }
            }
        }

        // 转换单位为GB（假设原始数据是MB）
        if (estimatedTraffic.compareTo(BigDecimal.ZERO) > 0) {
            estimatedTraffic = estimatedTraffic.divide(new BigDecimal(1024), 2, RoundingMode.HALF_UP);
        }
        aviationAppStatsVO.setEstimatedTraffic(estimatedTraffic);

        return aviationAppStatsVO;
    }

    @Override
    public List<AirPlaneAndDeviceInfoVO> publishByPlaneCodeDeviceInfo() {
        // 分组查询出飞机号及其对应的设备数量
        //查询已登记已注册,已关联飞机的设备
        List<TbDevice> tbDevices = tbDeviceMapper.selectList();
        // 按飞机号分组统计设备数量
        Map<String, Long> planeCodeDeviceCountMap = tbDevices.stream().collect(Collectors.groupingBy(TbDevice::getAirplaneCode, Collectors.counting()));


        // 转换为VO列表
        List<AirPlaneAndDeviceInfoVO> result = planeCodeDeviceCountMap.entrySet().stream().map(entry -> {
            AirPlaneAndDeviceInfoVO vo = new AirPlaneAndDeviceInfoVO();
            vo.setPlaneCode(entry.getKey());
            vo.setDeviceNum(entry.getValue().intValue());
            return vo;
        }).collect(Collectors.toList());

        return result;

    }

    @Override
    public List<AirPlaneAndDeviceDetailInfoVO> publishByDeviceSnDeviceInfo(String deviceSn, String planeCode) {
        List<AirPlaneAndDeviceDetailInfoVO> result = new ArrayList<>();

        // 1. 查询符合条件的飞机列表
        List<TbAirplane> tbAirplanes = tbAirplaneMapper.selectListByplaneCode(planeCode);
        if (tbAirplanes.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 遍历每架飞机，查询关联的设备信息
        for (TbAirplane tbAirplane : tbAirplanes) {
            // 获取该飞机关联的设备信息
            List<TbDeviceVO> deviceVOs = tbDeviceMapper.selectListByPlaneCode(tbAirplane.getPlaneCode(), deviceSn);

            if (!deviceVOs.isEmpty()) {
                // 3. 构造返回对象
                AirPlaneAndDeviceDetailInfoVO infoVO = new AirPlaneAndDeviceDetailInfoVO();
                infoVO.setAirplaneCode(tbAirplane.getPlaneCode());
                infoVO.setDeviceCount(deviceVOs.size());

                infoVO.setVos(deviceVOs);

                result.add(infoVO);
            }
        }

        return result;

    }


    @Override
    public TableDataInfo selectTbTaskVOLis(String taskName, Integer taskStatus, Date registrationTimeBegin, Date registrationTimeEnd) {

        // 1. 查询总记录数
        long total = tbTaskMapper.selectTbTaskCount(taskName, taskStatus,
                registrationTimeBegin, registrationTimeEnd);

        // 2. 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        // 3. 设置分页参数
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }

        // 4. 查询分页数据
        List<TbTaskResultVO> taskResults = tbTaskMapper.selectTbTaskLists(taskName, taskStatus,
                registrationTimeBegin, registrationTimeEnd);

        // 5. 转换为VO列表
        List<TbTaskVO> list = convertToVOList(taskResults);

        // 6. 返回TableDataInfo
        return getDataTable(list, total);
    }

    private TableDataInfo getDataTable(List<TbTaskVO> list, long total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        return rspData;
    }


    /**
     * 转换为VO列表
     */
    private List<TbTaskVO> convertToVOList(List<TbTaskResultVO> taskResults) {
        return taskResults.stream().map(taskResult -> {
            TbTaskVO vo = new TbTaskVO();

            // 复制基础属性
            BeanUtils.copyProperties(taskResult, vo);

            // 设置统计信息
            vo.setTaskItemCount(taskResult.getTaskItemCount());
            vo.setFailedDeviceCount(taskResult.getFailedDeviceCount());
            vo.setTotalDevices(taskResult.getTotalDevices());
            vo.setSuccessDevices(taskResult.getSuccessDevices());

            // 计算任务进度和进度详情
            calculateTaskProgress(vo);

            // 构建任务目标描述
            vo.setTaskTarget(buildTargetDescriptions(vo));

            return vo;
        }).collect(Collectors.toList());
    }


    /**
     * 计算任务进度
     */
    private void calculateTaskProgress(TbTaskVO vo) {
        if (vo.getTotalDevices() != null && vo.getTotalDevices() > 0) {
            double progress = ((double) vo.getSuccessDevices() / vo.getTotalDevices()) * 100;
            progress = Math.round(progress * 10) / 10.0; // 四舍五入保留1位小数
            vo.setTaskProgress(progress);
            vo.setProgressDetail(String.format("%d/%d", vo.getSuccessDevices(), vo.getTotalDevices()));
        } else {
            vo.setTaskProgress(0d);
            vo.setProgressDetail("0/0");
        }
    }

    /**
     * 构建任务目标描述
     */
    private String buildTargetDescriptions(TbTaskVO vo) {
        if (vo.getTotalDevices() != null && vo.getTotalDevices() > 0) {
            return String.format("%d架飞机(%d台设备)", vo.getTotalDevices(), vo.getTotalDevices());
        }
        return "0架飞机(0台设备)";
    }






    @Override
    @Transactional(rollbackFor = Exception.class)
    public R decommissionedInfoCreateTask(TaskUninstallDTO dto) {
        if (log.isDebugEnabled()) {
            log.debug("开始创建卸载任务: {}", dto);
        }
        try {
            // 参数验证
            validateTaskUnInstallDTO(dto);

            // 1. 获取目标设备ID列表
            List<Long> deviceIds = resolveTargetDeviceIds(dto);
            if (CollectionUtils.isEmpty(deviceIds)) {
                return R.fail("未找到目标设备");
            }
            // 2. 创建主任务
            TbTask task = createUninstallMainTask(dto);
            if (task == null || task.getId() == null) {
                return R.fail("创建主任务失败");
            }
            // 3. 创建任务详情
            List<TbTaskDetail> details = createUninstallTaskDetails(task, dto, deviceIds);
            if (CollectionUtils.isEmpty(details)) {
                throw new ServiceException("未创建任何任务详情");
            }
            // 4. 创建任务目标设备记录
            createTaskTargetDevices(details, deviceIds);

            if (log.isInfoEnabled()) {
                log.info("成功创建卸载任务, taskId: {}, 设备数量: {}", task.getId(), deviceIds.size());
            }

            return R.ok(task.getId(), "任务创建成功");
        } catch (ServiceException e) {
            log.warn("创建任务业务异常: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("创建任务系统异常: {}", e.getMessage(), e);
            return R.fail("系统异常，创建任务失败");
        }

    }

    @Override
    public Long selectTbTaskCount(String taskName, Integer taskStatus, Date registrationTimeBegin, Date registrationTimeEnd) {
        return  tbTaskMapper.selectTbTaskCount(taskName, taskStatus, registrationTimeBegin, registrationTimeEnd);
    }

    /**
     * 解析目标设备ID列表
     */
    private List<Long> resolveTargetDeviceIds(TaskUninstallDTO dto) {
        // 优先使用直接指定的设备ID
        if (CollectionUtils.isNotEmpty(dto.getDeviceIds())) {
            return dto.getDeviceIds();
        }

        // 其次使用飞机编码查询设备
        if (CollectionUtils.isNotEmpty(dto.getPlaneCodes())) {
            List<Long> deviceIds = tbDeviceMapper.selectTbDeviceSnBy(dto.getPlaneCodes());
            if (CollectionUtils.isNotEmpty(deviceIds)) {
                return deviceIds;
            }
        }

        // 最后使用全量卸载：根据应用名称查找所有安装了该应用的设备
        TbAppCatalog appCatalog = tbAppCatalogMapper.selectTbAppCatalogById(dto.getCatalogId());
        if (appCatalog == null) {
            throw new ServiceException("未找到对应的应用目录信息");
        }

        return tbDeviceAppsMapper.selectDeviceIdByAppName(appCatalog.getAppName());
    }

    /**
     * 参数验证
     */
    private void validateTaskUnInstallDTO(TaskUninstallDTO dto) {
        if (dto == null) {
            throw new ServiceException("参数不能为空");
        }

        if (dto.getCatalogId() == null) {
            throw new ServiceException("应用目录ID不能为空");
        }

        if (StringUtils.isBlank(dto.getTaskName())) {
            throw new ServiceException("任务名称不能为空");
        }

    }

    /**
     * 创建任务目标设备记录
     */
    private void createTaskTargetDevices(List<TbTaskDetail> details, List<Long> deviceIds) {
        if (CollectionUtils.isEmpty(details) || CollectionUtils.isEmpty(deviceIds)) {
            return;
        }

        String username = SecurityUtils.getUsername();
        Date now = new Date();
        List<TbTaskTarget> targets = new ArrayList<>(details.size() * deviceIds.size());

        for (TbTaskDetail detail : details) {
            for (Long deviceId : deviceIds) {
                TbTaskTarget target = new TbTaskTarget();
                target.setTaskDetailId(detail.getId());
                target.setDeviceId(deviceId);
                target.setStatus(0); // 待执行
                target.setRetryCount(0);
                target.setProgress(0.0);
                target.setCreateBy(username);
                target.setUpdateBy(username);
                target.setCreateTime(now);
                target.setUpdateTime(now);

                targets.add(target);
            }
        }
        // 批量插入，分批处理避免单次批量过大
        if (!targets.isEmpty()) {
            tbTaskTargetMapper.batchInsert(targets);
        }
    }

    /**
     * 创建卸载任务详情
     */
    private List<TbTaskDetail> createUninstallTaskDetails(TbTask task, TaskUninstallDTO dto, List<Long> deviceIds) {
        TbTaskDetail detail = new TbTaskDetail();
        detail.setTaskId(task.getId());
        detail.setTaskType(5); // 卸载任务类型
        detail.setPushPackageType(1);
        detail.setPackageId(dto.getCatalogId());

        // 获取应用名称
        String appName = tbAppCatalogMapper.selectAppNameById(dto.getCatalogId());
        detail.setAppName(StringUtils.isNotBlank(appName) ? appName : "未知应用");

        detail.setStatus(0);
        detail.setProgress(0.0);
        detail.setOrderId(1);
        detail.setDeviceCount(deviceIds.size());
        detail.setCreateTime(new Date());
        detail.setCreateBy(SecurityUtils.getUsername());
        tbTaskDetailMapper.insertTbTaskDetail(detail);
        return Collections.singletonList(detail);
    }

    /**
     * 创建主任务
     */
    private TbTask createUninstallMainTask(TaskUninstallDTO dto) {
        TbTask task = new TbTask();
        task.setTaskName(dto.getTaskName() + dto.getCatalogId());
        task.setTaskTargetDesc(dto.getTaskDescription());
        task.setTaskPriority(dto.getTaskPriority());
        task.setForceQuitApp(dto.getForceQuitApp());
        task.setUpdateIncompatible(dto.getUpdateIncompatible());
        task.setAutoRetry(dto.getAutoRetry());
        task.setOverwriteExist(dto.getOverwriteExist());
        task.setPushType(dto.getImmediatePush());
        task.setTaskProgress(0.0);
        task.setTaskStatus(1); // 任务状态：待执行
        task.setRegistrationTime(new Date());
        task.setCreateBy(SecurityUtils.getUsername());
        task.setCreateTime(new Date());

        // 插入数据库并返回带ID的实体
        tbTaskMapper.insertTbTask(task);
        return task;
    }




    private String buildTargetDescription(TbTaskVO query) {
        List<Map<String, Object>> groups = tbDeviceMapper.selectDeviceStatsByTask(query);
        int planeCount = groups.size();
        int deviceCount = groups.stream().mapToInt(g -> ((Number) g.get("deviceCount")).intValue()).sum();
        return String.format("%d架飞机(%d台设备)", planeCount, deviceCount);
    }


    // 参数校验
    private void validateTaskCreateDTO(TaskCreateDTO dto) {
        if (dto == null) {
            throw new IllegalArgumentException("任务创建参数不能为空");
        }
        if (StringUtils.isBlank(dto.getTaskName())) {
            throw new IllegalArgumentException("任务名称不能为空");
        }
        if (CollectionUtils.isEmpty(dto.getItems())) {
            throw new IllegalArgumentException("推送项不能为空");
        }

    }

    // 创建主任务
    private TbTask createMainTask(TaskCreateDTO dto) {
        TbTask tbTask = new TbTask();
        BeanUtils.copyProperties(dto, tbTask, "packageVersioncodes", "deviceIds");
        tbTask.setTaskTargetDesc(dto.getTaskDescription());

        tbTask.setPushType(dto.getImmediatePush());
        tbTask.setAutoRetry(dto.getAutoRetry());
        tbTask.setOverwriteExist(dto.getOverwriteExist());
        tbTask.setForceQuitApp(dto.getForceQuitApp());
        tbTask.setUpdateIncompatible(dto.getUpdateIncompatible());
        tbTask.setRegistrationTime(DateUtils.getNowDate());

        tbTask.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        tbTask.setCreateTime(DateUtils.getNowDate());

        if (tbTaskMapper.insertTbTask(tbTask) <= 0) {
            throw new RuntimeException("创建主任务失败");
        }
        return tbTask;
    }


}
